import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/dashboard'
  },
  {
    path: '/dashboard',
    name: 'Dashboard',
    component: () => import('../views/Dashboard.vue')
  },
  {
    path: '/http-client',
    name: 'HttpClient',
    component: () => import('../modules/http-client/HttpClient.vue')
  },
  {
    path: '/http-server',
    name: 'HttpServer', 
    component: () => import('../modules/http-server/HttpServer.vue')
  },
  {
    path: '/mqtt-client',
    name: 'MqttClient',
    component: () => import('../modules/mqtt-client/MqttClient.vue')
  },
  {
    path: '/websocket',
    name: 'WebSocket',
    component: () => import('../modules/websocket/WebSocket.vue')
  },
  {
    path: '/tcp-client',
    name: 'TcpClient',
    component: () => import('../modules/tcp-client/TcpClient.vue')
  },
  {
    path: '/tcp-server',
    name: 'TcpServer',
    component: () => import('../modules/tcp-server/TcpServer.vue')
  },
  {
    path: '/udp-client',
    name: 'UdpClient',
    component: () => import('../modules/udp-client/UdpClient.vue')
  },
  {
    path: '/udp-server',
    name: 'UdpServer',
    component: () => import('../modules/udp-server/UdpServer.vue')
  },
  {
    path: '/json-formatter',
    name: 'JsonFormatter',
    component: () => import('../modules/tools/JsonFormatter.vue')
  },
  {
    path: '/base64',
    name: 'Base64',
    component: () => import('../modules/tools/Base64.vue')
  },
  {
    path: '/timestamp',
    name: 'Timestamp',
    component: () => import('../modules/tools/Timestamp.vue')
  },
  {
    path: '/history',
    name: 'History',
    component: () => import('../views/History.vue')
  },
  {
    path: '/settings',
    name: 'Settings',
    component: () => import('../views/Settings.vue')
  }
]

const router = new VueRouter({
  mode: process.env.IS_ELECTRON ? 'hash' : 'history',
  base: process.env.BASE_URL,
  routes
})

// 处理路由重复导航错误
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject) {
    return originalPush.call(this, location, onResolve, onReject)
  }
  return originalPush.call(this, location).catch(err => {
    if (err.name !== 'NavigationDuplicated') {
      throw err
    }
  })
}

const originalReplace = VueRouter.prototype.replace
VueRouter.prototype.replace = function replace(location, onResolve, onReject) {
  if (onResolve || onReject) {
    return originalReplace.call(this, location, onResolve, onReject)
  }
  return originalReplace.call(this, location).catch(err => {
    if (err.name !== 'NavigationDuplicated') {
      throw err
    }
  })
}

export default router